<?php

namespace app\api\controller;

use support\Request;
use plugin\saiadmin\app\logic\system\SystemUploadfileLogic;
use plugin\saiadmin\exception\ApiException;
use app\service\CosService;

class UploadController
{
    /**
     * 上传图片
     */
    public function image(Request $request)
    {
        try {
            // 检查是否有上传文件
            $files = $request->file();
            if (empty($files)) {
                throw new ApiException('请选择要上传的图片');
            }

            $logic = new SystemUploadfileLogic();
            $result = $logic->uploadBase('image');
            $check = CosService::imageContentCheck($result['storage_path']);
            if ($check['suggestion'] === 'Pass') {
                if (isset($result['url'])) {
                    return json([
                        'code' => 200,
                        'msg' => '上传成功',
                        'data' => [
                            'url' => $result['url'],
                            'filename' => $result['origin_name'],
                            'check' => $check
                        ]
                    ]);
                }
            } else {
                return json(['code' => 400, 'msg' => '图片审核失败，请上传合规图片', 'data' => $check]);
            }
            
            return json(['code' => 400, 'msg' => '上传失败']);
        } catch (\Exception $e) {
            return json(['code' => 400, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 上传文件
     */
    public function file(Request $request)
    {
        try {
            // 检查是否有上传文件
            $files = $request->file();
            if (empty($files)) {
                throw new ApiException('请选择要上传的文件');
            }

            $logic = new SystemUploadfileLogic();
            $result = $logic->uploadBase('file');
            
            // 文件审核
            if (isset($result['storage_path']) && file_exists($result['storage_path'])) {
                $check = CosService::imageContentCheck($result['storage_path']);
            } else {
                $check = CosService::imageContentCheck($result['url']);
            }

            if ($check['suggestion'] === 'Pass') {
                if (isset($result['url'])) {
                    return json([
                        'code' => 200,
                        'msg' => '上传成功',
                        'data' => [
                            'url' => $result['url'],
                            'filename' => $result['origin_name'],
                            'check' => $check
                        ]
                    ]);
                }
            } else {
                return json(['code' => 400, 'msg' => '文件审核失败，请上传合规文件', 'data' => $check]);
            }
            
            return json(['code' => 400, 'msg' => '上传失败']);
        } catch (\Exception $e) {
            return json(['code' => 400, 'msg' => $e->getMessage()]);
        }
    }
}
